import random
from django.shortcuts import HttpResponse, render
from utils.tencent.sms import send_sms_single

from django.conf import settings


# Create your views here.


def send_sms(request):
    """发送短信
    ?:tpl=login  -->  1701114
    ?:tpl=register  -->  1701115
    """
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:  # 没找到模板
        return HttpResponse('模板不存在')
    code = random.randrange(1000, 9999)
    res = send_sms_single('17713995975', template_id, [code, ])
    print(res)
    if res['result'] == 0:
        return HttpResponse('成功')
    else:
        return HttpResponse(res['errmsg'])


from django import forms
from app01 import models
from django.core.validators import RegexValidator


class RegisterModelform(forms.ModelForm):
    # RegexValidator 添加re正则
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$'), '手机号格式错误'])
    # widget 修改输入类
    password = forms.CharField(label='密码', widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入密码'}))
    # django会检测数据库中有没有字段，有则覆盖，没有就添加
    confirm_password = forms.CharField(
        label='重复密码', widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'placeholder': '请输入确认密码'
            }), )
    code = forms.CharField(label='验证码', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入验证码'}))

    class Meta:
        model = models.UserInfo
        # fields = "__all__"    # 默认显示
        fields = [
            'username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code'
        ]

    # 重写父类init方法
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = f'请输入{field.label}'


def register(request):
    form = RegisterModelform()
    return render(request, 'app01/register.html', {'form': form})
